//
//  ClubSquareSettingViewController.swift
//  77Club
//
//  Created by Apple on 2024/12/26.
//

import UIKit

class ClubSquareSettingViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("管理论坛").color(.black).font(16.font_semiBold).end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubSquareSettingItemCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 64.0.Scale
        return tableView
    }()
    
    var banNum = 0
    var adminNum = 0
    var memberNum = 0
    var master_user: ClubForumMemberModel?
    var dataSource = [ClubSquareSettingModel]()
    var communityId = "" {
        didSet{
            loadData()
        }
    }
    
    var updateData:(()->())?
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.updateData?()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            titleLabel
            tableView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.leading(56)
        titleLabel.CenterY == backButton.CenterY
        tableView.fillContainer().top(.navi_height).bottom(.safe_bottom)
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
    }

}

extension ClubSquareSettingViewController: UITableViewDelegate, UITableViewDataSource  {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareSettingItemCell", for: indexPath) as! ClubSquareSettingItemCell
        cell.model = dataSource[indexPath.row]
        cell.updateBanState = { state in
            Task{
                ToastUtil.show()
                let models = await self.network.requestSpecial(.editSquareInfo(gid: self.communityId, field: "is_ban", value: state))
                ToastUtil.dismiss()
                if models.isSuccess {
                    var showStr = "禁言成功~"
                    if state == "0"{
                        showStr = "已取消禁言~"
                    }
                    showStr.toast_success
                }else{
                    models.errorMessage?.toast_error
                }
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row == 0 {
            //论坛名称
            let nameVC = ClubChangeSquareNameViewController()
            nameVC.nameStr = dataSource[0].content
            nameVC.communityId = communityId
            nameVC.updateSquareName = { name in
                self.dataSource[0].content = name
                self.tableView.reloadData()
            }
            self.navigationController?.pushViewController(nameVC, animated: true)
        }else if indexPath.row == 1 {
            //论坛介绍
            let infoVC = ClubEditSquareInfoViewController()
            infoVC.infoStr = dataSource[1].content
            infoVC.communityId = communityId
            infoVC.updateSquareInfo = { info in
                self.dataSource[1].content = info
                self.tableView.reloadData()
            }
            self.navigationController?.pushViewController(infoVC, animated: true)
        }else if indexPath.row == 2 {
            //论坛公告
            let noticeVC = ClubEditSquareNoticeViewController()
            noticeVC.noticeStr = dataSource[2].content
            noticeVC.communityId = communityId
            noticeVC.updateSquareNotice = { notice in
                self.dataSource[2].content = notice
                self.tableView.reloadData()
            }
            self.navigationController?.pushViewController(noticeVC, animated: true)
        }else if indexPath.row == 3 || indexPath.row == 5 || indexPath.row == 6 {
            //人员禁言
            let memberVC = ClubSquareMemberViewController()
            memberVC.isAdmin = false
            memberVC.isMute = true
            memberVC.isShowBan = true
            memberVC.isShowManager = true
            memberVC.communityId = communityId
            memberVC.master_user = master_user
            memberVC.memberNum = self.memberNum
            memberVC.adminNum = self.adminNum
            memberVC.banNum = self.banNum
            if indexPath.row == 3 {
                memberVC.selIndex = 1
            }else if indexPath.row == 5 {
                memberVC.selIndex = 2
            }else{
                memberVC.selIndex = 0
            }
            memberVC.updateSquareMember = {
                self.loadData()
            }
            self.navigationController?.pushViewController(memberVC, animated: true)
        }else if indexPath.row == 7 {
            //论坛背景图
            let bgVC = ClubChangeBgViewController()
            bgVC.communityId = communityId
            bgVC.bgImgUrl = dataSource[7].bgImg
            bgVC.updateSquareBgImg = { imgUrl in
                self.dataSource[7].bgImg = imgUrl
                self.tableView.reloadData()
            }
            self.navigationController?.pushViewController(bgVC, animated: true)
        }else if indexPath.row == 8 {
            //论坛logo
            let logoVC = ClubChangeLogoViewController()
            logoVC.communityId = communityId
            logoVC.logoUrl = dataSource[8].logo
            logoVC.updateSquareLogo = { logoUrl in
                self.dataSource[8].logo = logoUrl
                self.tableView.reloadData()
            }
            self.navigationController?.pushViewController(logoVC, animated: true)
        }else if indexPath.row == 9 {
            //关注设置
            let settingVC = ClubFollowSettingViewController()
            settingVC.communityId = communityId
            settingVC.model = dataSource[9]
            settingVC.updateSquareSetting = { model in
                self.dataSource[9] = model
                self.tableView.reloadData()
            }
            self.navigationController?.pushViewController(settingVC, animated: true)
        }
    }
}

//MARK: data
extension ClubSquareSettingViewController {
    
    private func loadData(){
        Task {
            ToastUtil.show()
            dataSource.removeAll()
            let res = await network.request(.communityTop(communityID: communityId),type: ClubGameCommunityModel.self)
            ToastUtil.dismiss()
            if res.isSuccess, let model = res.model {
                self.master_user = model.master_user
                let nameMd = ClubSquareSettingModel(title: "论坛名称", content: model.name)
                dataSource.append(nameMd)
                var infoContent = model.content
                if infoContent.count <= 0 {
                    infoContent = "未设置"
                }
                let infoMd = ClubSquareSettingModel(title: "论坛介绍", content: infoContent)
                dataSource.append(infoMd)
                var noticeContent = model.notice
                if noticeContent.count <= 0 {
                    noticeContent = "未设置"
                }
                let noticeMd = ClubSquareSettingModel(title: "论坛公告", content: noticeContent)
                dataSource.append(noticeMd)
                var banNumber = ClubGlobalTool.shared.formatNumber(num: "\(model.ban_num)")
                self.banNum = model.ban_num
                if banNumber == "0" {
                    banNumber = ""
                }else{
                    banNumber = banNumber + "人"
                }
                let banNumberMd = ClubSquareSettingModel(title: "人员禁言", content: banNumber)
                dataSource.append(banNumberMd)
                let banMd = ClubSquareSettingModel(title: "论坛禁言", isBan: model.is_ban == 1)
                dataSource.append(banMd)
                var managerNumber = ClubGlobalTool.shared.formatNumber(num: "\(model.admin_num)")
                self.adminNum = model.admin_num
                if managerNumber == "0" {
                    managerNumber = "未添加"
                }else{
                    managerNumber = managerNumber + "人"
                }
                let managerNumberMd = ClubSquareSettingModel(title: "管理员", content: managerNumber)
                dataSource.append(managerNumberMd)
                var guanzhuNum = ClubGlobalTool.shared.formatNumber(num: "\(model.guanzhu_num)")
                self.memberNum = model.guanzhu_num
                if guanzhuNum == "0" {
                    guanzhuNum = ""
                }else{
                    guanzhuNum = guanzhuNum + "人"
                }
                let guanzhuNumMd = ClubSquareSettingModel(title: "论坛成员", content: guanzhuNum)
                dataSource.append(guanzhuNumMd)
                let bgImgMd = ClubSquareSettingModel(title: "论坛背景图", bgImg: model.bgimg)
                dataSource.append(bgImgMd)
                let logoMd = ClubSquareSettingModel(title: "论坛logo", logo: model.icon)
                dataSource.append(logoMd)
                var setting = model.settings
                if setting.count <= 0 {
                    setting = "未设置"
                }
                let settingMd = ClubSquareSettingModel(title: "关注设置", content: setting, logo: "\(model.guanzhu_num)", bgImg: model.system_type)
                dataSource.append(settingMd)
                
                self.tableView.reloadData()
            }
        }
    }
}
